package com.bytesizedhosting.api.android.darthcrap.screens;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bytesizedhosting.api.android.darthcrap.Constants;
import com.bytesizedhosting.api.android.darthcrap.ExtendedActivity;
import com.bytesizedhosting.api.android.darthcrap.FocusSolver;
import com.bytesizedhosting.api.android.darthcrap.R;

public class KeySetScreen extends ExtendedActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.keysetscreen);
        final Activity objActivity = this;
        TextView objTextview = (TextView)findViewById(R.id.txtKeyEntry);
        objTextview.setFilters(new InputFilter[]{new InputFilter() {
			@Override
			public CharSequence filter(CharSequence strSource, int intStart, int intEnd, Spanned strDest, int intDStart, int intDEnd) {
				if (strSource == null) {
					return null;
				}
				for (int intCharacter=intStart; intCharacter<intEnd; intCharacter++) {
					char chrCurrent = strSource.charAt(intCharacter);
					if (!((chrCurrent >= '0' && chrCurrent <= '9') || (chrCurrent >= 'a' && chrCurrent <= 'f') || (chrCurrent >= 'A' && chrCurrent <= 'F'))) {
						return "";
					}
				}
				return strSource.toString().toLowerCase();
			}
		}});
		SharedPreferences objSettings = objActivity.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE);
		String strAPIKey = objSettings.getString(Constants.PREFS_KEY_APIKEY, "");
		if (strAPIKey.matches("[0-9a-f]{40}")) {
			objTextview.setText(strAPIKey);
		}
		else {
			objTextview.setText("");
		}
        findViewById(R.id.btnSave).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View objView) {
				String strKey = ((TextView)findViewById(R.id.txtKeyEntry)).getText().toString();
				if (strKey.matches("([0-9a-f]{40})")) {
					SharedPreferences.Editor objEditor = getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE).edit();
					objEditor.putString(Constants.PREFS_KEY_APIKEY, strKey);
					objEditor.commit();
					objActivity.setResult(Activity.RESULT_OK);
					Toast.makeText(objActivity, objActivity.getString(R.string.keyset_message_saved), Toast.LENGTH_SHORT).show();
					objActivity.finish();					
				}
				else {
					Toast.makeText(objActivity, objActivity.getString(R.string.keyset_message_notvalid), Toast.LENGTH_SHORT).show();					
				}
			}
		});
        findViewById(R.id.btnCancel).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View objView) {
				objActivity.setResult(Activity.RESULT_CANCELED);
				objActivity.finish();
			}
		});
        objTextview.setOnFocusChangeListener(new FocusSolver(this));
        findViewById(R.id.btnKeyQR).setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View objView) {
				try {
					Intent objIntent = new Intent("la.droid.qr.scan");
					objIntent.putExtra("la.droid.qr.complete", false);
					startActivityForResult(objIntent,0);
				}
				catch (ActivityNotFoundException objException) {
					new AlertDialog.Builder(objActivity)
					.setCancelable(true)
					.setMessage(objActivity.getString(R.string.keyset_message_noqrdroid))
					.setNegativeButton(objActivity.getString(R.string.generic_no),new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface objDialog, int intID) {
							objDialog.cancel();
						}
					})
					.setPositiveButton(objActivity.getString(R.string.generic_yes),new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface objDialog, int intID) {
							objActivity.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=la.droid.qr")));
						}
					})
					.create().show();
				}
			}
		});
    }
    
    public void onActivityResult(int intRequestCode, int intResultCode, Intent objIntent) { 
    	if (intRequestCode == 0 && intResultCode != RESULT_CANCELED) {
    		String strResult = objIntent.getStringExtra("la.droid.qr.result");
    		Matcher objMatcher = Pattern.compile("([0-9a-f]{40})([0-9a-f]{8})").matcher(strResult);
    		boolean boolValid = false;
    		if (objMatcher.matches()) {
    			CRC32 objChecksummer = new CRC32();
    			objChecksummer.update(objMatcher.group(1).toLowerCase().getBytes());
    			String strCRC = Long.toHexString(objChecksummer.getValue()).toLowerCase();
    			if (objMatcher.group(2).toLowerCase().equals(strCRC)) {
        			boolValid = true;
        			((TextView)findViewById(R.id.txtKeyEntry)).setText(objMatcher.group(1).toLowerCase());
        			Toast.makeText(this, this.getString(R.string.keyset_message_qraccepted), Toast.LENGTH_SHORT).show();
    			}
    		}
    		if (!boolValid) {
				new AlertDialog.Builder(this)
				.setCancelable(true)
				.setMessage(this.getString(R.string.keyset_message_qrdeclined))
				.setNeutralButton(this.getString(R.string.generic_ok),new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface objDialog, int intID) {
						objDialog.cancel();
					}
				})
				.create().show();
    		}
    	}
    }
}